package com.controller;

import com.entity.Buser;
import com.mapper.BuserMapper;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/admin")//后台控制器
public class AdminController {

    @Autowired
    BuserMapper buserMapper;

    @GetMapping("/login")
    public String login() {
        return "back/login";
    }

    @PostMapping("/toLogin")
    public String toLogin(Buser buser, Model model, HttpSession session){
        String username = buser.getUsername();
        String password = buser.getPassword();

        // 使用 MyBatis-Flex 的 QueryWrapper 构造查询条件（修复后）
//        QueryWrapper queryWrapper = QueryWrapper.create()
//                .select()
//                .and("username", username)
//                .and("password", password);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Buser::getUsername, username);
        queryWrapper.eq(Buser::getPassword, password);
        Buser buser1 = buserMapper.selectOneByQuery(queryWrapper);
        if (buser1 != null) {
            session.setAttribute("admin", buser1); // 登录成功，保存用户信息
            return "back/index";
        } else {
            model.addAttribute("msg", "用户名或密码错误");
            return "back/login"; // 返回登录页面
        }
    }


    @GetMapping("/welcome")
    public String welcome() {
        return "back/welcome";
    }

    @GetMapping("/logout") // 退出登录
    public String logout(HttpSession session){
        session.removeAttribute("admin");
        return "back/login";
    }
}
